<template>
    <div>
        <form action="/">
            <van-search type="search" v-model="name" show-action placeholder="大家都在搜 减肥" @input="onSearch"
            :loading="loading"
            @cancel="onCancel" />
        </form>
        <div class="content">
            <div class="course-list" v-for="item in value" :key="item.pid">
                <img :src="base + item.pic" alt="">
                <div>
                    <h3>{{ item.title }}</h3>
                    <p>k1 零基础 · {{ item.duration }}分钟</p>
                </div>
                <van-icon name="add-o" size="22" color="#666" @click="courseAdd(item.pid)" />
            </div>
        </div>
    </div>
</template>

<script>
import httpApi from '@/http';
import { base } from '@/service'
import { Toast } from 'vant';
import storage from '@/utils/Storage';

export default {
    data() {
        return {
            value: {
                pic: '',
                title: '',
                duration: '',
                pid: ''
            },
            loading: false,
            name: '',
            base,
        };
    },
    methods: {
        onCancel(){
            this.$router.push('/my/course')
        },
        onSearch(val) {
            if (val == '') {
                this.value = {}
                return
            }
            this.courseSearch(val)
        },

        courseSearch(val) {

            this.loading = true
            // 发请求，模糊查询
            httpApi.courseApi.courserByName({ title: val }).then(res => {
                console.log('模糊查询结果', res)
                this.value = res.data.data
            })

        },
        courseAdd(id) {
            console.log(id);
            let params = { course_id: id, uid:  storage.get(storage.KEY_USER).uid }
            httpApi.userApi.courseUserAdd(params).then(res => {
                console.log(res);
                if (res.data.code == 200) {
                    Toast('新增成功');
                }else{
                    Toast('课程已添加,不能重复添加')
                }
            })
        }
    },
    mounted() {
        this.value = {}
    }
}
</script>

<style lang="scss">
.content {
    padding: 2vh;

    .course-list {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 2vh;

        img {
            width: 30vw;
            border-radius: 10px;
            height: 10vh;
            object-fit: cover;
        }

        div {
            margin-right: 10vw;
        }

        h3 {
            color: #333;
            width: 40vw;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            font-size: 18px;
        }

        p {
            color: #666;
            font-size: 14px;
            margin-top: 1vh;
        }
    }
}
</style>
<style>
* {
    padding: 0;
    margin: 0;
}

img {
    display: block;
}
</style>